package org.gntc.prayer;

import org.gntc.prayer.database.PrayerDB;
import org.gntc.prayer.database.PrayerDBInfo.PrayerTable;
import org.gntc.prayer.R;

import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteException;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

public class PrayerListActivity extends ListActivity {
	private PrayerDB mPrayerDB;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		
	}

	@Override
	protected void onResume() {
		initDB();
		
		Cursor c = mPrayerDB.getAllPrayer();
		String[] from = new String[] {PrayerTable.TITLE};
		int[] to = {android.R.id.text1};
		SimpleCursorAdapter adapter = new SimpleCursorAdapter(PrayerListActivity.this, android.R.layout.simple_list_item_1, c, from, to);
		setListAdapter(adapter);
		super.onResume();
	}
	private void initDB() {
		mPrayerDB = new PrayerDB(PrayerListActivity.this);
		try {
			mPrayerDB.open();
		} catch (SQLiteException e) {
			e.printStackTrace();
		}
	}
	
	@Override
	public boolean onCreateOptionsMenu (Menu menu)
	{
		MenuInflater inflater = new MenuInflater(PrayerListActivity.this);
		inflater.inflate(R.menu.prayer_list_menu, menu);
		return super.onCreateOptionsMenu(menu);
	}
	
	@Override
	public boolean onOptionsItemSelected (MenuItem item)
	{
		switch (item.getItemId())
		{
		case R.id.new_prayer :
			gotoEditPrayerActivity();
			break;

		default :
			break;
		}
		return super.onOptionsItemSelected(item);
	}
	
	private void gotoEditPrayerActivity(){
		Intent intent = new Intent(PrayerListActivity.this, EditPrayerActivity.class);
		startActivityForResult(intent, 0);
	}
	
	@Override
	protected void onListItemClick (ListView listview, View view, int position, long id)
	{
		// TODO Auto-generated method stub
		SimpleCursorAdapter adapter = (SimpleCursorAdapter) getListAdapter();
		Cursor cursor = adapter.getCursor();
		cursor.moveToPosition(position);
		int index = cursor.getInt(cursor.getColumnIndex(PrayerTable._ID));
		
		Intent intent = new Intent(PrayerListActivity.this, ViewPrayerActivity.class);
		intent.putExtra("id", index);
		startActivity(intent);
		
		super.onListItemClick(listview, view, position, id);
	}
	
	@Override
	protected void onPause() {
		mPrayerDB.close();
		super.onPause();
	}
}